const createError = require('http-errors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const logger = require('morgan');
const ArtTemplate = require('express-art-template')

const config = require('./config/index.js')
const Headers = require('./util/header.js')
const indexRouter = require('./routes');

const app = express();

app.use(Headers)
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ArtTemplate)
app.set('view engine', 'html')
app.use(logger('dev---------'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//定义一个cookie和session组合使用的配置对象
app.use(cookieParser('express'));
app.use(session({
  secret: 'express',
  resave: false,
  saveUninitialized: true,
  store: MongoStore.create({
    mongoUrl:`${config.host}:${config.port}/${config.basedata}`,
    touchAfter: 3600  //过期时间
  }),
  rolling: true,
  cookie: {
    httpOnly: true,//开启后前端无法通过js操作session
    maxAge: 1000*60*60*24*7
  }
}));

app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
